<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="计划人员配置" v-model="visible" append-to-body width="900px" @close="handleClose">
    <el-button type="primary" class="mb-3" @click="() => addRef.open()">新增</el-button>

    <vxe-table ref="tableRef" :data="data" :loading="loadings.query">
      <vxe-column type="seq" :width="60"></vxe-column>
      <vxe-column title="部门" :min-width="80">
        <template #default="{ row }">
          <VCascader v-model="row.department_id" type="1" placeholder="请选择" class="w-full" />
        </template>
      </vxe-column>
      <vxe-column title="计划人员" :min-width="80">
        <template #default="{ row }">
          <VCascader v-model="row.plan_user_id" placeholder="请选择" class="w-full" />
        </template>
      </vxe-column>
      <vxe-column title="操作" :width="100">
        <template #default="{ row, rowIndex }">
          <el-button link type="primary" :loading="loadings['submit' + rowIndex]" @click="submit(row)">保存</el-button>
          <el-button link type="danger" @click="remove(row.puc_id)">删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
    </template>
    <Add ref="addRef" :options="options" @success="query" />
  </el-dialog>
</template>

<script setup>
import Add from './Add'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const api = inject('api')
const load = ref(false)
const visible = ref(false)
const addRef = ref(false)
let loadings = reactive({})
const data = ref([])

const emit = defineEmits(['close', 'success'])

const query = async () => {
  loadings.query = true
  const res = await api.planList()
  loadings.query = false
  data.value = res.data
}

// 打开弹窗
const open = async (is_ids) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  query()
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const remove = async (puc_id) => {
  ElMessageBox.confirm('是否确认删除？', '取消', {
    confirmButtonClass: 'messagebox-confirm-button',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      loadings.remove = true
      try {
        await api.deletePlan({ puc_id })
        ElMessage.success('操作成功')
        query()
      } catch (error) {
        ElMessage.error(error)
      }
      loadings.remove = false
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消操作', })
    })
}

// 提交
const submit = (row, rowIndex) => {
  loadings['submit' + rowIndex] = true
  api.savePlan(row).then(res => {
    ElMessage.success('操作成功')
  }).finally(() => {
    loadings['submit' + rowIndex] = false
  })
}

defineExpose({ open })
</script>